<!-- excel 导入组件 -->
<template>
	<el-dialog :title="prop.title" v-model="state.upload.open" :close-on-click-modal="false" draggable>
		<div class="time">
			<el-date-picker v-model="detectionTime" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间"
				v-if="isMedical" format="YYYY-MM-DD" date-format="YYYY/MM/DD" />
		</div>
		<el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="headers" v-loading="loading"
			:action="baseURL + other.adaptationUrl(url)" :disabled="state.upload.isUploading"
			:on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :on-error="handleFileError"
			:auto-upload="false" drag :data="computedData">
			<i class="el-icon-upload"></i>
			<div class="el-upload__text">
				{{ $t('excel.operationNotice') }}
				<em>{{ $t('excel.clickUpload') }}</em>
			</div>
			<template #tip>
				<div class="el-upload__tip text-center">
					<span>{{ $t('excel.fileFormat') }}</span>
					<el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
						@click="downExcelTemp" v-if="tempUrl">{{ $t('excel.downloadTemplate') }}
					</el-link>
				</div>
			</template>
		</el-upload>
		<template #footer>
			<el-button type="primary" :disabled="disabledbtn" @click="submitFileForm">{{ $t('common.confirmButtonText')
				}}</el-button>
			<el-button @click="state.upload.open = false" :disabled="disabledbtn">{{ $t('common.cancelButtonText')
				}}</el-button>
		</template>
	</el-dialog>

	<!--校验失败错误数据-->
	<el-dialog :title="$t('excel.validationFailureData')" v-model="state.errorVisible">
		<el-table :data="state.errorData">
			<el-table-column property="lineNum" :label="$t('excel.lineNumbers')" width="100"></el-table-column>
			<el-table-column property="errors" :label="$t('excel.misDescription')" show-overflow-tooltip>
				<template v-slot="scope">
					<el-tag type="danger" v-for="error in scope.row.errors" :key="error">{{ error }}</el-tag>
				</template>
			</el-table-column>
		</el-table>
	</el-dialog>
</template>

<script setup lang="ts" name="upload-excel">
import { useMessage } from '/@/hooks/message';
import other from '/@/utils/other';
import { Session } from '/@/utils/storage';
import { formatDate } from '/@/utils/formatTime';
// import { fa } from 'element-plus/es/locale';

const emit = defineEmits(['sizeChange', 'refreshDataList']);
const loading = ref(false)
const prop = defineProps({
	url: {
		type: String,
	},
	title: {
		type: String,
	},
	tempUrl: {
		type: String,
	},
	isMedical: {
		type: Boolean,
		default: false,
	},
});
const disabledbtn = ref(false)
const uploadRef = ref();

const detectionTime = ref([]);
const state = reactive({
	errorVisible: false,
	errorData: [],
	dialog: {
		title: '',
		isShowDialog: false,
	},
	upload: {
		open: false,
		isUploading: false,
	},
});

/**
 * 下载模板文件
 */
const downExcelTemp = () => {
	other.downBlobFile(other.adaptationUrl(prop.tempUrl), {}, 'temp.xlsx');
};

const computedData = computed(() => {
	if (prop.isMedical) {
		return {
			startTime: detectionTime.value[0] ? formatDate(new Date(detectionTime.value[0]), 'YYYY-mm-dd HH:MM:SS') : '',
			endTime: detectionTime.value[1] ? formatDate(new Date(detectionTime.value[1]), 'YYYY-mm-dd HH:MM:SS') : '',
		};
	}
	return null;
});
const getData = () => {
	console.log(props.isMedical);
	if (props.isMedical) {
		return {
			startTime: detectionTime[0],
			endTime: detectionTime[1],
		};
	} else {
		return null;
	}
};
/**
 * 上传进度条变化事件
 */
const handleFileUploadProgress = () => {
	loading.value = true
	disabledbtn.value = true
	state.upload.isUploading = true;
};

/**
 * 上传失败事件处理
 */


/**
 * 上传成功事件处理
 * @param {any} response - 上传成功的响应结果
 */

// const handleFileError = (err, file ) => {
// 	console.log(err)
// 	// useMessage().error(response.msg);
// 	state.upload.open = false;
// };
const handleFileError = (err, file) => {
	// err 是上传失败的错误对象
	console.error('上传错误:', err);

	if (err instanceof Error) {
		console.log('错误信息:', JSON.parse(err.message));
		useMessage().error("上传超时，数据量太大，请减少数据重新上传");
		state.upload.open = false;
		loading.value = false
	} else {
		// 解析返回的错误信息
		try {
			const errorResponse = JSON.parse(err);
			console.log('具体错误代码:', errorResponse.code);
			console.log('具体错误信息:', errorResponse.msg);
			state.upload.open = false;
			loading.value = false
		} catch (parseError) {
			console.error('解析错误信息失败:', parseError);
			state.upload.open = false;
			loading.value = false
		}
	}
}
const handleFileSuccess = (response: any) => {
	state.upload.isUploading = false;
	state.upload.open = false;
	loading.value = false
	disabledbtn.value = false
	uploadRef.value.clearFiles();

	// 校验失败
	if (response.code === 1) {
		useMessage().error(response.msg);
		state.errorVisible = true;
		state.errorData = response.data;
		uploadRef.value.clearFiles();
		loading.value = false
		disabledbtn.value = false
		// 刷新表格
		emit?.('refreshDataList');
	} else {
		useMessage().success(response.msg ? response.msg : '导入成功');
		loading.value = false
		disabledbtn.value = false
		// 刷新表格
		emit?.('refreshDataList');
	}
};

/**
 * 提交表单，触发上传
 */
const submitFileForm = () => {
	try {
		uploadRef.value.submit();

	} catch (e) {
		console.log(e)
	}
};

/**
 * 显示上传文件对话框，并清除上传信息
 */
const show = () => {
	state.upload.isUploading = false;
	state.upload.open = true;
};

/**
 * 计算请求头部信息
 */
const headers = computed(() => {
	return {
		Authorization: 'Bearer ' + Session.getToken(),
		'TENANT-ID': Session.getTenant(),
	};
});

// 暴露变量
defineExpose({
	show,
});
</script>

<style scoped>
.time {
	margin-bottom: 20px;
}
</style>
